package com.sse.security;

import java.io.*;
import java.security.*;
import java.security.spec.*;

class VerSig {

	public static void main(String[] args) {

		/* Verify a DSA signature */

		if (args.length != 3) {
			System.out
					.println("Usage: VerSig publickeyfile signaturefile datafile");
		} else
			try {
				
				/* input the signature bytes */
				FileInputStream sigfis = new FileInputStream(args[1]);
				byte[] sigToVerify = new byte[sigfis.available()];
				sigfis.read(sigToVerify);
				sigfis.close();

				FileInputStream datafis = new FileInputStream(args[2]);
				byte[] data = new byte[datafis.available()];
				datafis.read(data);
				datafis.close();

				boolean verifies = verify(sigToVerify,data);

				System.out.println("signature verifies: " + verifies);

			} catch (Exception e) {
				System.err.println("Caught exception " + e.toString());
			}

	}

	public static boolean verify(byte[] sigToVerify, byte[] data)
			throws NoSuchAlgorithmException, NoSuchProviderException,
			InvalidKeyException, SignatureException, InvalidKeySpecException {

		byte[] encKey = getPublicKey();

		X509EncodedKeySpec pubKeySpec = new X509EncodedKeySpec(encKey);
		KeyFactory keyFactory = KeyFactory.getInstance("DSA", "SUN");
		PublicKey pubKey = keyFactory.generatePublic(pubKeySpec);

		Signature sig = Signature.getInstance("SHA1withDSA", "SUN");
		sig.initVerify(pubKey);

		sig.update(data, 0, 8);

		boolean verifies = sig.verify(sigToVerify);

		return verifies;
	}

	public static byte[] getPublicKey() throws NoSuchAlgorithmException,
			NoSuchProviderException, InvalidKeyException, SignatureException {

		KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DSA", "SUN");

		SecureRandom random = SecureRandom.getInstance("SHA1PRNG", "SUN");

		int seed = 1234;
		random.setSeed(seed);

		keyGen.initialize(512, random);

		KeyPair pair = keyGen.generateKeyPair();
		PublicKey pub = pair.getPublic();

		byte[] key = pub.getEncoded();

		return key;
	}

}
